<template>
  <el-dialog
    v-model="visible"
    title="资产比对结果"
    width="1400px"
    @close="handleClose"
    destroy-on-close
  >
    <div class="comparison-content">
      <el-card style="margin-bottom: 16px">
        <div class="info-row">
          <div style="display: flex; align-items: center">
            <span class="label">任务:</span>
            <span class="value">{{ taskName }}</span>
            <span class="label" style="margin-left: 20px">同步时间:</span>
            <span class="value">{{ syncTime }}</span>
          </div>
          <div style="flex: 1; display: flex; justify-content: flex-end">
            <el-dropdown @command="handleExportCommand">
              <el-button type="primary">
                导出修正后的资产表
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="all">导出全部</el-dropdown-item>
                  <el-dropdown-item command="normal"
                    >仅导出正常端口</el-dropdown-item
                  >
                  <el-dropdown-item command="exclude-severe"
                    >排除严重异常</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-card>
      <!-- 头部信息 -->
      <!-- 筛选器和统计 -->
      <el-card shadow="never" style="margin-bottom: 16px">
        <div class="filter-section">
          <DynamicForm
            ref="searchFormRef"
            v-model="searchForm"
            :form-config="searchFormConfig"
            :gutter="16"
            label-width="100px"
            type="search"
            @search="handleSearch"
            @reset="handleReset"
          />
        </div>

        <!-- 统计信息 -->
        <div v-if="statistics.total_ips > 0" class="statistics-section">
          <div class="stat-row">
            <span class="stat-label">统计:</span>
            <span class="stat-text"
              >共{{ statistics.total_ips }}个IP,
              {{ statistics.total_ports }}条端口记录</span
            >
          </div>
          <div class="stat-tags">
            <el-tag type="danger" size="small"
              >🔴远程异常:{{ statistics.remote_open || 0 }}</el-tag
            >
            <el-tag type="warning" size="small"
              >🟡超范围:{{ statistics.out_of_range || 0 }}</el-tag
            >
            <el-tag type="info" size="small"
              >🔵双端丢失:{{ statistics.both_missing || 0 }}</el-tag
            >
            <el-tag size="small"
              >⚪仅本地:{{ statistics.local_only || 0 }}</el-tag
            >
            <el-tag type="success" size="small"
              >🟢正常:{{ statistics.normal || 0 }}</el-tag
            >
          </div>
        </div>
      </el-card>

      <!-- IP卡片列表 -->
      <div class="ip-cards-container" v-loading="loading">
        <div v-for="record in ipRecords" :key="record.ip" class="ip-card">
          <div class="ip-card-header" @click="toggleExpand(record)">
            <div class="ip-info">
              <span class="ip-label">📊 IP:</span>
              <span class="ip-value">{{ record.ip }}</span>
            </div>
            <div class="ip-stats">
              <span class="port-count"
                >共{{ record.ports?.length || 0 }}个端口</span
              >
              <span
                v-if="getPortStats(record).remote_open > 0"
                class="stat-badge danger"
                >🔴远程异常:{{ getPortStats(record).remote_open }}</span
              >
              <span
                v-if="getPortStats(record).out_of_range > 0"
                class="stat-badge warning"
                >🟡超范围:{{ getPortStats(record).out_of_range }}</span
              >
              <span
                v-if="getPortStats(record).both_missing > 0"
                class="stat-badge info"
                >🔵双端丢失:{{ getPortStats(record).both_missing }}</span
              >
              <span
                v-if="getPortStats(record).local_only > 0"
                class="stat-badge"
                >⚪仅本地:{{ getPortStats(record).local_only }}</span
              >
              <span
                v-if="getPortStats(record).normal > 0"
                class="stat-badge success"
                >🟢正常:{{ getPortStats(record).normal }}</span
              >
            </div>
            <el-icon class="expand-icon" :class="{ expanded: record.expanded }">
              <ArrowDown />
            </el-icon>
          </div>

          <!-- 资产信息 -->
          <div v-if="record.expanded" class="ip-card-body">
            <div class="asset-info-section">
              <div class="section-title">资产信息:</div>
              <div class="info-grid">
                <div class="info-item">
                  <span class="info-label">资产名称:</span>
                  <span class="info-value">{{ record.asset_name || "-" }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">资产类型:</span>
                  <span class="info-value">{{ record.asset_type || "-" }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">所属部门:</span>
                  <span class="info-value">{{ record.department || "-" }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">责任人:</span>
                  <span class="info-value">{{
                    record.contact_person || "-"
                  }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">网管已知端口:</span>
                  <span class="info-value">{{
                    record.network_ports || "-"
                  }}</span>
                </div>
              </div>
            </div>

            <!-- 端口列表 -->
            <div class="ports-section">
              <div class="section-title">端口列表:</div>
              <el-table
                :data="record.ports"
                border
                stripe
                size="small"
                style="width: 100%"
              >
                <el-table-column
                  prop="port"
                  label="端口"
                  width="100"
                  align="center"
                />
                <el-table-column label="状态" width="120" align="center">
                  <template #default="{ row }">
                    <el-tag
                      :type="getExceptionTypeTag(row.exception_type)"
                      size="small"
                    >
                      {{ getExceptionTypeText(row.exception_type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="本地" width="80" align="center">
                  <template #default="{ row }">
                    <span
                      :class="
                        row.local_validation ? 'check-success' : 'check-fail'
                      "
                    >
                      {{ row.local_validation ? "✓" : "✗" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="远程" width="80" align="center">
                  <template #default="{ row }">
                    <span
                      :class="
                        row.external_validation ? 'check-success' : 'check-fail'
                      "
                    >
                      {{ row.external_validation ? "✓" : "✗" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="note" label="备注" minWidth="200" />
                <el-table-column
                  label="操作"
                  width="150"
                  align="center"
                  fixed="right"
                >
                  <template #default="{ row }">
                    <el-button
                      type="primary"
                      link
                      size="small"
                      @click="handleEditPort(row, record)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      size="small"
                      @click="handleDeletePort(row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && ipRecords.length === 0"
          description="暂无数据"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          :layout="pagination.layout"
          :background="pagination.background"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 编辑端口对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑端口"
      width="500px"
      @close="handleCloseEditDialog"
    >
      <el-form ref="editFormRef" :model="editForm" label-width="100px">
        <el-form-item label="端口号">
          <el-input v-model="editForm.port" placeholder="请输入端口号" />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-select
            v-model="editForm.exception_type"
            placeholder="请选择异常类型"
            style="width: 100%"
          >
            <el-option label="正常" value="normal" />
            <el-option label="远程异常" value="remote_open" />
            <el-option label="超范围" value="out_of_range" />
            <el-option label="双端丢失" value="both_missing" />
            <el-option label="仅本地" value="local_only" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="editForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit" :loading="saving"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import {
  querySyncRecords,
  editSyncRecord,
  exportAsUploadFormat,
} from "@/api/task";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { PaginationConfig } from "@/components/DynamicTable/types";

interface Props {
  modelValue: boolean;
  runId: string;
  taskName?: string;
  syncTime?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  runId: "",
  taskName: "",
  syncTime: "",
});

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  close: [];
}>();

const visible = ref(false);
const loading = ref(false);
const saving = ref(false);
const searchFormRef = ref<DynamicFormInstance>();
const editFormRef = ref();
const ipRecords = ref<any[]>([]);
const statistics = ref({
  total_ips: 0,
  total_ports: 0,
  remote_open: 0,
  out_of_range: 0,
  both_missing: 0,
  local_only: 0,
  normal: 0,
});

const searchForm = reactive({
  exception_type: null as string | null,
  ip_search: "",
});

const searchFormConfig: FormItemConfig[] = [
  {
    key: "exception_type",
    name: "异常类型",
    type: "select",
    placeholder: "全部",
    options: [
      { label: "全部", value: null },
      { label: "🔴远程异常", value: "remote_open" },
      { label: "🟡超范围", value: "out_of_range" },
      { label: "🔵双端丢失", value: "both_missing" },
      { label: "⚪仅本地", value: "local_only" },
      { label: "🟢正常", value: "normal" },
    ],
    params: {
      clearable: true,
      style: { width: "150px" },
    },
  },
  {
    key: "ip_search",
    name: "IP搜索",
    type: "input",
    placeholder: "请输入IP地址",
    col: {
      span: 6,
    },
    params: {
      clearable: true,
      style: { width: "200px" },
    },
  },
];

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const editDialogVisible = ref(false);
const editForm = reactive({
  id: 0,
  port: "",
  exception_type: "",
  note: "",
});

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal && props.runId) {
      loadSyncRecords();
    }
  }
);

// 监听 visible 变化
watch(visible, (newVal) => {
  if (!newVal) {
    emit("update:modelValue", false);
    emit("close");
  }
});

// 加载比对结果
const loadSyncRecords = async () => {
  if (!props.runId) {
    ElMessage.warning("run_id不存在");
    return;
  }

  loading.value = true;
  try {
    const params: any = {
      run_id: props.runId,
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    };

    if (searchForm.exception_type) {
      params.exception_type = searchForm.exception_type;
    }

    if (searchForm.ip_search) {
      params.ip_search = searchForm.ip_search;
    }

    const { data } = await querySyncRecords(params);

    ipRecords.value = (data.records || []).map((record: any) => ({
      ...record,
      expanded: true, // 默认折叠
    }));
    pagination.total = data.total || 0;
    statistics.value = data.statistics || {
      total_ips: 0,
      total_ports: 0,
      remote_open: 0,
      out_of_range: 0,
      both_missing: 0,
      local_only: 0,
      normal: 0,
    };
  } catch (error: any) {
    console.error("查询比对结果失败:", error);
    ElMessage.error("查询比对结果失败");
  } finally {
    loading.value = false;
  }
};

// 切换展开/折叠
const toggleExpand = (record: any) => {
  record.expanded = !record.expanded;
};

// 获取端口统计
const getPortStats = (record: any) => {
  const stats = {
    remote_open: 0,
    out_of_range: 0,
    both_missing: 0,
    local_only: 0,
    normal: 0,
  };

  record.ports?.forEach((port: any) => {
    if (port.exception_type) {
      stats[port.exception_type as keyof typeof stats] =
        (stats[port.exception_type as keyof typeof stats] || 0) + 1;
    }
  });

  return stats;
};

// 获取异常类型标签
const getExceptionTypeTag = (type: string | null) => {
  const typeMap: Record<string, string> = {
    remote_open: "danger",
    out_of_range: "warning",
    both_missing: "info",
    local_only: "",
    normal: "success",
  };
  return typeMap[type || ""] || "";
};

// 获取异常类型文本
const getExceptionTypeText = (type: string | null) => {
  const typeMap: Record<string, string> = {
    remote_open: "🔴 远程异常",
    out_of_range: "🟡 超范围",
    both_missing: "🔵 双端丢失",
    local_only: "⚪ 仅本地",
    normal: "🟢 正常",
  };
  return typeMap[type || ""] || "-";
};

// 搜索
const handleSearch = (value: any) => {
  searchForm.exception_type = value.exception_type ?? null;
  searchForm.ip_search = value.ip_search || "";
  pagination.currentPage = 1;
  loadSyncRecords();
};

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.exception_type = null;
  searchForm.ip_search = "";
  pagination.currentPage = 1;
  loadSyncRecords();
};

// 分页变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  loadSyncRecords();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadSyncRecords();
};

// 编辑端口
const handleEditPort = (port: any, record: any) => {
  editForm.id = port.id;
  editForm.port = port.port;
  editForm.exception_type = port.exception_type || "";
  editForm.note = port.note || "";
  editDialogVisible.value = true;
};

// 删除端口
const handleDeletePort = (port: any) => {
  ElMessageBox.confirm("确定要删除这条端口记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await editSyncRecord({
          id: port.id,
          action: "delete",
        });
        ElMessage.success("删除成功");
        await loadSyncRecords();
      } catch (error: any) {
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
  } catch {
    return;
  }

  saving.value = true;
  try {
    await editSyncRecord({
      id: editForm.id,
      action: "update",
      port: editForm.port,
      exception_type: editForm.exception_type,
      note: editForm.note,
    });
    ElMessage.success("修改成功");
    editDialogVisible.value = false;
    await loadSyncRecords();
  } catch (error: any) {
    ElMessage.error(error.message || "修改失败");
  } finally {
    saving.value = false;
  }
};

// 关闭编辑对话框
const handleCloseEditDialog = () => {
  editForm.id = 0;
  editForm.port = "";
  editForm.exception_type = "";
  editForm.note = "";
};

// 导出命令处理
const handleExportCommand = (command: string) => {
  let excludeExceptions: string[] = [];

  switch (command) {
    case "all":
      excludeExceptions = [];
      break;
    case "normal":
      excludeExceptions = [
        "remote_open",
        "out_of_range",
        "both_missing",
        "local_only",
      ];
      break;
    case "exclude-severe":
      excludeExceptions = ["remote_open", "both_missing"];
      break;
  }

  handleExport(excludeExceptions);
};

// 导出
const handleExport = async (excludeExceptions?: string[]) => {
  if (!props.runId) {
    ElMessage.warning("run_id不存在");
    return;
  }

  try {
    const exclude = excludeExceptions?.join(",") || "";
    const blob = await exportAsUploadFormat({
      run_id: props.runId,
      exclude_exceptions: exclude,
    });

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `网管资产同步结果-${new Date().getTime()}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error: any) {
    console.error("导出失败:", error);
    ElMessage.error(error.message || "导出失败");
  }
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};

// 暴露导出方法供父组件调用
defineExpose({
  handleExport,
});
</script>

<style lang="scss" scoped>
.comparison-content {
  padding: 10px 0;
  height: 680px;
  overflow-y: auto;
}

.header-info {
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;

  .info-row {
    display: flex;
    align-items: center;

    .label {
      font-weight: 500;
      color: #606266;
      margin-right: 8px;
    }

    .value {
      color: #303133;
    }
  }
}

.filter-section {
  margin-bottom: 16px;
}

.statistics-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;

  .stat-row {
    margin-bottom: 12px;

    .stat-label {
      font-weight: 500;
      color: #606266;
      margin-right: 8px;
    }

    .stat-text {
      color: #303133;
    }
  }

  .stat-tags {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
  }
}

.ip-cards-container {
  min-height: 200px;
}

.ip-card {
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .ip-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    background: #f8f9fa;
    cursor: pointer;
    user-select: none;

    .ip-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .ip-label {
        font-weight: 500;
        color: #606266;
      }

      .ip-value {
        font-weight: 600;
        color: #303133;
        font-size: 16px;
      }
    }

    .ip-stats {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1;
      margin-left: 20px;

      .port-count {
        color: #909399;
        font-size: 14px;
      }

      .stat-badge {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;

        &.danger {
          background: #fef0f0;
          color: #f56c6c;
        }

        &.warning {
          background: #fdf6ec;
          color: #e6a23c;
        }

        &.info {
          background: #f4f4f5;
          color: #909399;
        }

        &.success {
          background: #f0f9ff;
          color: #67c23a;
        }
      }
    }

    .expand-icon {
      transition: transform 0.3s;
      color: #909399;

      &.expanded {
        transform: rotate(180deg);
      }
    }
  }

  .ip-card-body {
    padding: 16px;
    background: #fff;
  }
}

.asset-info-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;

  .section-title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 12px;

    .info-item {
      display: flex;
      align-items: center;

      .info-label {
        font-weight: 500;
        color: #606266;
        min-width: 100px;
        margin-right: 8px;
      }

      .info-value {
        color: #303133;
      }
    }
  }
}

.ports-section {
  .section-title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 12px;
  }
}

.check-success {
  color: #67c23a;
  font-weight: bold;
}

.check-fail {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
